package com.hjy.core.transport.netty.server;

import com.hjy.common.hook.ShutdownHook;
import com.hjy.core.codec.CommonCodec;
import com.hjy.core.nacos.NacosServiceRegistry;
import com.hjy.core.nacos.ServiceRegistry;
import com.hjy.core.provider.DefaultServiceProvider;
import com.hjy.core.provider.ServiceProvider;
import com.hjy.core.serializer.CommonSerializer;
import com.hjy.core.serializer.JsonSerializer;
import com.hjy.core.serializer.KryoSerializer;
import com.hjy.core.transport.AbstractRpcServer;
import com.hjy.core.transport.RpcServer;
import com.hjy.core.transport.netty.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.net.InetSocketAddress;

/**
 * netty 服务器端
 */
@Data
public class NettyServer extends AbstractRpcServer {

    private CommonSerializer serializer;

    /**
     * 默认使用 KryoSerializer
     * @param host
     * @param port
     */
    public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
        serviceRegistry = new NacosServiceRegistry();
        serviceProvider = new DefaultServiceProvider();
        serializer = new KryoSerializer();
        scanServices();
    }

    public NettyServer(String host, int port, CommonSerializer serializer) {
        this.host = host;
        this.port = port;
        serviceRegistry = new NacosServiceRegistry();
        serviceProvider = new DefaultServiceProvider();
        this.serializer = serializer;
        scanServices();
    }

    @Override
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG, 256)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1 << 20, 12, 4, 0, 0));
                            pipeline.addLast(new CommonCodec(serializer));
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(port).sync();
            // 结束时清除nacos的信息
            ShutdownHook.getShutdownHook().addClearAllHook();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            System.err.println("启动服务器时有错误发生: " + e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
